package com.emuporium.gymrat.server.data;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

//Shamelessly stolen from Murach's Java Servlets and JSP 2nd Edition
public class UserDB {
	public static int insert(User user, String password) {
		ConnectionPool pool = ConnectionPool.getInstance();
		Connection connection = pool.getConnection();
		PreparedStatement ps = null;
		ResultSet rs = null;

		if (emailExists(user.getEmail()))
			return 0;

		String query = "INSERT INTO account (email, password, admin)"
				+ "VALUES (?, ?, ?)";
		try {
			ps = connection.prepareStatement(query);
			ps.setString(1, user.getEmail());
			ps.setString(2, password);
			ps.setBoolean(3, user.isAdmin());
			return ps.executeUpdate();
		} catch (SQLException e) {
			e.printStackTrace();
			return 0;
		} finally {
			DBUtil.closeResultSet(rs);
			DBUtil.closePreparedStatement(ps);
			pool.freeConnection(connection);
		}
	}

	public static boolean emailExists(String emailAddress) {
		ConnectionPool pool = ConnectionPool.getInstance();
		Connection connection = pool.getConnection();
		PreparedStatement ps = null;
		ResultSet rs = null;

		String query = "SELECT email FROM account " + "WHERE email = ?";
		try {
			ps = connection.prepareStatement(query);
			ps.setString(1, emailAddress);
			rs = ps.executeQuery();
			return rs.next();
		} catch (SQLException e) {
			e.printStackTrace();
			return false;
		} finally {
			DBUtil.closeResultSet(rs);
			DBUtil.closePreparedStatement(ps);
			pool.freeConnection(connection);
		}
	}

	// This method returns null if a record isn't found.
	public static User selectUser(String emailAddress) {
		ConnectionPool pool = ConnectionPool.getInstance();
		Connection connection = pool.getConnection();
		PreparedStatement ps = null;
		ResultSet rs = null;

		String query = "SELECT * FROM account " + "WHERE email = ?";
		
		try {
			ps = connection.prepareStatement(query);
			ps.setString(1, emailAddress);
			rs = ps.executeQuery();
			User user = null;
			if (rs.next()) {
				user = new User();
				user.setEmail(rs.getString("email"));
				user.setId(rs.getInt("_id"));
				user.setAdmin(rs.getBoolean("admin"));
			}
			return user;
		} catch (SQLException e) {
			e.printStackTrace();
			return null;
		} finally {
			DBUtil.closeResultSet(rs);
			DBUtil.closePreparedStatement(ps);
			pool.freeConnection(connection);
		}
	}
}